package cn.schoolwow.quickdao.module.database.dml.instance.flow.delete;

import cn.schoolwow.quickdao.domain.database.dml.UpdateType;
import cn.schoolwow.quickdao.domain.entity.Entity;
import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickdao.module.database.dml.common.domain.ManipulationOption;
import cn.schoolwow.quickdao.module.database.dml.instance.flow.delete.common.DeleteByMultipleUniqueFieldNameFlow;
import cn.schoolwow.quickdao.module.database.dml.instance.flow.delete.common.DeleteByMultipleUniqueKeyFlow;
import cn.schoolwow.quickdao.module.database.dml.instance.flow.delete.common.DeleteBySingleUniqueKeyFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

public class DeleteInstanceFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        Entity entity = (Entity) flowContext.checkData("entity");
        ManipulationOption manipulationOption = flowContext.checkInstanceData(ManipulationOption.class);
        UpdateType updateType = flowContext.checkInstanceData(UpdateType.class);

        switch (updateType){
            case UpdateByUniqueFieldName:{
                if(manipulationOption.uniqueFieldNames.size()==1){
                    String uniqueFieldName = manipulationOption.uniqueFieldNames.iterator().next();
                    Property property = entity.getPropertyByFieldNameOrColumnName(uniqueFieldName);
                    flowContext.startFlow(new DeleteBySingleUniqueKeyFlow())
                            .putTemporaryData("uniqueKeyProperty", property)
                            .execute();
                }else{
                    flowContext.executeFlowList(new DeleteByMultipleUniqueFieldNameFlow());
                }
            }break;
            case UpdateByUniqueKey:{
                if(entity.uniqueProperties.size()==1){
                    Property uniqueKeyProperty = entity.uniqueProperties.get(0);
                    flowContext.startFlow(new DeleteBySingleUniqueKeyFlow())
                            .putTemporaryData("uniqueKeyProperty", uniqueKeyProperty)
                            .execute();
                }else{
                    flowContext.executeFlowList(new DeleteByMultipleUniqueKeyFlow());
                }
            }break;
            case UpdateById:{
                flowContext.startFlow(new DeleteBySingleUniqueKeyFlow())
                        .putTemporaryData("uniqueKeyProperty", entity.id)
                        .execute();
            }break;
        }
    }

    @Override
    public String name() {
        return "删除实例";
    }

}
